import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Tag, Space, Tooltip } from 'antd';
import { PlusOutlined, CloseOutlined } from '@ant-design/icons';

/**
 * 场地设施编辑组件
 * 用于动态增删场地设施
 * @param {Object} props
 * @param {Array} props.value - 当前设施列表
 * @param {Function} props.onChange - 值变化回调
 */
const FacilityEditor = ({ value = [], onChange }) => {
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [facilities, setFacilities] = useState([]);
  const inputRef = React.useRef(null);

  // 初始化设施列表
  useEffect(() => {
    if (Array.isArray(value)) {
      setFacilities(value);
    } else if (typeof value === 'string' && value) {
      try {
        // 尝试解析JSON字符串
        const parsedValue = JSON.parse(value);
        setFacilities(Array.isArray(parsedValue) ? parsedValue : []);
      } catch (error) {
        // 如果不是JSON格式，尝试按逗号分隔
        const facilityArray = value.split(',').map(item => item.trim()).filter(Boolean);
        setFacilities(facilityArray);
        console.error('解析设施数据失败，按逗号分隔处理:', error);
      }
    } else {
      setFacilities([]);
    }
  }, [JSON.stringify(value)]);

  // 显示输入框
  const showInput = () => {
    setInputVisible(true);
    setTimeout(() => {
      inputRef.current?.focus();
    }, 100);
  };

  // 处理输入框确认
  const handleInputConfirm = () => {
    if (inputValue && !facilities.includes(inputValue)) {
      const newFacilities = [...facilities, inputValue];
      setFacilities(newFacilities);
      onChange(JSON.stringify(newFacilities));
    } else{
      setInputVisible(false);
      setInputValue('');
    }
  };

  // 处理删除设施
  const handleClose = (removedFacility) => {
    const newFacilities = facilities.filter(facility => facility !== removedFacility);
    setFacilities(newFacilities);
    onChange(JSON.stringify(newFacilities));
  };

  return (
    <div className="facility-editor">
      <Space size={[0, 8]} wrap>
        {facilities.map((facility) => (
          <Tag
            key={facility}
            closable
            onClose={() => handleClose(facility)}
            style={{ marginBottom: 8 }}
          >
            {facility}
          </Tag>
        ))}
        {inputVisible ? (
          <Input
            ref={inputRef}
            type="text"
            size="small"
            style={{ width: 120, marginBottom: 8 }}
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onBlur={handleInputConfirm}
            onPressEnter={handleInputConfirm}
            placeholder="请输入设施名称"
          />
        ) : (
          <Tag 
            onClick={showInput} 
            style={{ marginBottom: 8, borderStyle: 'dashed', cursor: 'pointer' }}
          >
            <PlusOutlined /> 添加设施
          </Tag>
        )}
      </Space>
    </div>
  );
};

export default FacilityEditor;